import React from 'react';
import { Modal } from 'antd';
import CreateForm from '@/components/CreateForm';
import CreateTable from '@/components/CreateTable';
import TableTool from '@/components/CreateTable/TableTool';
import { assignDefaultFormData, filterFormData } from '@/components/Common/utils';

interface ModalProps {
  modalConfig: {
    visible: boolean;
    showReset?: boolean; // 字段和form保证一致性
    showSubmit?: boolean;
    title?: string;
    footer?: any;
    [propName: string]: any;
  };
}

class CreateModal extends React.PureComponent<ModalProps> {
  private bindFormRef: any;

  public state = {
    prevVisible: false,
  };

  /**
   * 静态方法，控制当前状态visible状态
   * @param nextProps
   */
  static getDerivedStateFromProps(nextProps: any, prevState: any) {
    const { modalConfig } = nextProps;
    // 当子项中有表单时，进行监测
    if (modalConfig.hasOwnProperty('formConfig') && modalConfig.formConfig.config) {
      // new CreateModal(nextProps).resetFormFields(modalConfig.visible);
      if (modalConfig.visible !== prevState.prevVisible) {
        return {
          prevVisible: modalConfig.visible,
        };
      }
    }
    return null;
  }

  /**
   * 判断弹窗关闭时，重置表单
   * @param prevProps
   * @param prevState
   */
  componentDidUpdate(prevProps: any, prevState: any) {
    if (!this.state.prevVisible && this.state.prevVisible !== prevState.prevVisible) {
      this.resetFormFields();
    }
  }

  /**
   * 统一进行重置表单
   * @param data
   */
  resetFormFields = () => {
    if (this.bindFormRef) this.bindFormRef.resetFields();
  };

  /**
   * 关闭弹窗的回掉方法
   * @param key
   * @param callback
   */
  beforeCloseCallBack = (key?: string, callback?: Function) => {
    const { modalConfig } = this.props;

    /**
     * ⚠ 关闭弹窗主要通过footer的按钮，以及弹窗中的关闭X来执行
     * ⚠ 在footer传参数时对回掉方法重新绑定了一次，目的是为了获取子表单对数据
     */
    const doCallBack = (params = {}) => {
      if (callback) {
        callback(params);

        // 判断modalConfig是否有回掉方法
      } else if (modalConfig.closeModalCallBack) {
        modalConfig.closeModalCallBack(params);
      }
    };

    let params = {};
    // 判断modal中是否含有form，如有form需要对form数据进行处理
    if (key && modalConfig.hasOwnProperty('formConfig')) {
      if (key === 'reset') {
        params = assignDefaultFormData(modalConfig);

        doCallBack(params);
      }

      if (key === 'submit') {
        this.bindFormRef.validateFields((error: any, value: {}) => {
          if (!error) {
            params = assignDefaultFormData(modalConfig, true);

            filterFormData(value, modalConfig.formConfig);

            // 将默认参数和Form参数合并
            params = Object.assign({}, params, value);

            doCallBack(params);
          }
        });
      }
      // 如果没有form, 执行回掉
    } else {
      doCallBack(params);
    }
  };

  handleConfirm = () => {};

  renderModalBody = () => {
    const { modalConfig, children } = this.props;
    const modalBody = [];
    // 针对于渲染form
    if (modalConfig.hasOwnProperty('formConfig') && modalConfig.formConfig.config) {
      let { formConfig } = modalConfig;
      formConfig = { ...formConfig, isPopup: true, layout: 'horizontal' };
      modalBody.push(
        <CreateForm
          key="CreateForm"
          ref={(ref: any) => {
            this.bindFormRef = ref;
          }}
          formConfig={formConfig}
        />,
      );
    }

    // 针对渲染table
    if (modalConfig.hasOwnProperty('tableConfig') && modalConfig.tableConfig.header) {
      const { tableConfig } = modalConfig;
      modalBody.push(<CreateTable tableConfig={tableConfig} key="CreateTable" />);
    }

    // 如果子集
    if (children) {
      modalBody.push(children);
    }

    return modalBody;
  };

  render() {
    const { modalConfig } = this.props;
    const { config = {}, showReset = false, showSubmit = false, footer } = modalConfig;

    const defaultFormFooterOptions = [
      {
        name: '取消',
        auth: showReset,
        event: {
          click: this.beforeCloseCallBack.bind(this),
        },
      },
      {
        name: '确定',
        auth: showSubmit,
        event: {
          click: this.handleConfirm.bind(this),
        },
      },
    ];

    if (footer && footer.length) {
      footer.forEach((item: any) => {
        if (item.event && item.event.click) {
          // 需要把之前的方法进行一次储存，当作回掉方法，方便表单的数据返回
          const oldClick = item.event.click;
          item.event.click = (e: any) => {
            e.preventDefault();
            e.stopPropagation();
            this.beforeCloseCallBack(item.id || 'reset', oldClick);
          };
        }
      });
    }

    // 默认的footer
    const Footer = <TableTool options={footer || defaultFormFooterOptions} />;

    const defaultConfig = {
      title: modalConfig.title || (modalConfig.isEdit ? '编辑' : '新增'),
      centered: true, // 居中显示
      maskClosable: false, // 点击modal关闭
      keyboard: false, // esc关闭
      footer: Footer,
      ...config,
    };

    return (
      <Modal
        {...defaultConfig}
        visible={modalConfig.visible}
        onCancel={() => this.beforeCloseCallBack('reset')}
        width={modalConfig.width || 700}
      >
        {this.renderModalBody()}
      </Modal>
    );
  }
}

export default CreateModal;
